package com.bj58.mis.apm.server.kylin.common.hllc;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

public class DenseRegister implements Register, Serializable {
    private int m;
    private byte[] register;

    public DenseRegister(int p) {
        this.m = 1 << p;
        this.register = new byte[this.m];
    }

    public void set(int pos, byte value) {
        this.register[pos] = value;
    }

    public byte get(int pos) {
        return this.register[pos];
    }

    public void merge(Register another) {
        if (another.getRegisterType() == RegisterType.DENSE) {
            DenseRegister dr = (DenseRegister)another;

            for(int i = 0; i < this.register.length; ++i) {
                if (dr.register[i] > this.register[i]) {
                    this.register[i] = dr.register[i];
                }
            }
        } else if (another.getRegisterType() == RegisterType.SPARSE) {
            SparseRegister sr = (SparseRegister)another;
            Collection<Map.Entry<Integer, Byte>> allValue = sr.getAllValue();
            Iterator i$ = allValue.iterator();

            while(i$.hasNext()) {
                Map.Entry<Integer, Byte> entry = (Map.Entry)i$.next();
                if ((Byte)entry.getValue() > this.register[(Integer)entry.getKey()]) {
                    this.register[(Integer)entry.getKey()] = (Byte)entry.getValue();
                }
            }
        } else {
            SingleValueRegister sr = (SingleValueRegister)another;
            if (sr.getSize() > 0 && sr.getValue() > this.register[sr.getSingleValuePos()]) {
                this.register[sr.getSingleValuePos()] = sr.getValue();
            }
        }

    }

    public void clear() {
        byte zero = 0;
        Arrays.fill(this.register, zero);
    }

    public int getSize() {
        int size = 0;

        for(int i = 0; i < this.m; ++i) {
            if (this.register[i] > 0) {
                ++size;
            }
        }

        return size;
    }

    public RegisterType getRegisterType() {
        return RegisterType.DENSE;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        } else if (obj == null) {
            return false;
        } else if (this.getClass() != obj.getClass()) {
            return false;
        } else {
            DenseRegister other = (DenseRegister)obj;
            return Arrays.equals(this.register, other.register);
        }
    }
    @Override
    public int hashCode() {
        return super.hashCode();
    }

    public byte[] getRawRegister() {
        return this.register;
    }
}
